<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气查询</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f4f9;
            text-align: center;
            padding-top: 50px;
        }

        input {
            padding: 12px 15px;
            margin: 8px;
            border: 1px solid #ccc;
            border-radius: 8px;
            font-size: 16px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }

        input:focus {
            border-color: #007BFF;
            outline: none;
            box-shadow: 0 0 8px rgba(0, 123, 255, 0.4);
        }

        button {
            padding: 12px 15px;
            margin: 8px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            background-color: #007BFF;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #0056b3;
        }

        ul {
            list-style-type: none;
            padding: 0;
            width: 80%;
            max-width: 600px;
            margin: 20px auto;
        }

        li {
            margin: 15px 0;
            background-color: white;
            border: none;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: box-shadow 0.3s ease;
        }

        li p {
            margin: 5px 0;
            display: flex;
            align-items: center;
        }

        li p span {
            margin-left: 10px;
        }

        li:hover {
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
        }

        button.delete {
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button.delete:hover {
            background-color: #c82333;
        }

        h1 {
            color: #333;
            margin-bottom: 30px;
        }
    </style>
</head>

<body>
    <h1>天气查询</h1>
    <input type="text" id="cityInput" placeholder="请输入城市名称">
    <button id="queryButton">查询</button>
    <button id="forecastButton">查询未来 3 天天气预报</button>
    <ul id="weatherList"></ul>
    <div id="forecastInfo"></div>

    <script>
        const weatherList = document.getElementById('weatherList');
        const forecastInfo = document.getElementById('forecastInfo');
        // 从 localStorage 中恢复数据
        function restoreData() {
            const storedData = localStorage.getItem('weatherData');
            if (storedData) {
                const dataArray = JSON.parse(storedData);
                dataArray.forEach(data => {
                    const listItem = document.createElement('li');
                    if (data.error) {
                        listItem.textContent = `查询 ${data.city} 出错: ${data.error}`;
                    } else {
                        listItem.innerHTML = `
                            <div>
                                <p><span>城市:</span> ${data.city}</p>
                                <p><span>天气:</span> ${data.weather}</p>
                                <p><span>温度:</span> ${data.temperature} °C</p>
                            </div>
                        `;
                    }

                    const deleteButton = document.createElement('button');
                    deleteButton.textContent = '删除';
                    deleteButton.classList.add('delete');
                    deleteButton.addEventListener('click', function () {
                        weatherList.removeChild(listItem);
                        updateLocalStorage();
                    });

                    listItem.appendChild(deleteButton);
                    weatherList.appendChild(listItem);
                });
            }
        }

        // 更新 localStorage
        function updateLocalStorage() {
            const listItems = weatherList.querySelectorAll('li');
            const dataArray = [];
            listItems.forEach(listItem => {
                const cityElement = listItem.querySelector('p:first-child span + text');
                if (cityElement) {
                    const city = cityElement.textContent.trim();
                    const weatherElement = listItem.querySelector('p:nth-child(2) span + text');
                    const temperatureElement = listItem.querySelector('p:nth-child(3) span + text');
                    if (weatherElement && temperatureElement) {
                        const weather = weatherElement.textContent.trim();
                        const temperature = temperatureElement.textContent.trim().replace(' °C', '');
                        dataArray.push({ city, weather, temperature });
                    } else {
                        const error = listItem.textContent.split(': ')[1];
                        dataArray.push({ city, error });
                    }
                }
            });
            localStorage.setItem('weatherData', JSON.stringify(dataArray));
        }

        document.getElementById('queryButton').addEventListener('click', async function () {
            const city = document.getElementById('cityInput').value;
            if (!city) {
                alert('请输入城市名称');
                return;
            }

            try {
                const apiUrl = `http://localhost:3000/weather?city=${city}`;
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }

                const data = await response.json();
                const listItem = document.createElement('li');

                if (data.error) {
                    listItem.textContent = `查询 ${city} 出错: ${data.error}`;
                } else {
                    listItem.innerHTML = `
                        <div>
                            <p><span>城市:</span> ${data.city}</p>
                            <p><span>天气:</span> ${data.weather}</p>
                            <p><span>温度:</span> ${data.temperature} °C</p>
                        </div>
                    `;
                    // 清空输入框
                    document.getElementById('cityInput').value = '';
                }

                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.classList.add('delete');
                deleteButton.addEventListener('click', function () {
                    weatherList.removeChild(listItem);
                    updateLocalStorage();
                });

                listItem.appendChild(deleteButton);
                // 将列表项插入到最上面
                weatherList.prepend(listItem);
                updateLocalStorage();

            } catch (error) {
                const listItem = document.createElement('li');
                listItem.textContent = `查询出错: ${error.message}`;

                const deleteButton = document.createElement('button');
                deleteButton.textContent = '删除';
                deleteButton.classList.add('delete');
                deleteButton.addEventListener('click', function () {
                    weatherList.removeChild(listItem);
                    updateLocalStorage();
                });

                listItem.appendChild(deleteButton);
                weatherList.prepend(listItem);
                updateLocalStorage();
            }
        });

        document.getElementById('forecastButton').addEventListener('click', async function () {
            const city = document.getElementById('cityInput').value;
            if (!city) {
                alert('请输入城市名称');
                return;
            }

            try {
                const apiUrl = `http://localhost:3000/forecast?city=${city}`;
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }

                const data = await response.json();
                if (data.error) {
                    forecastInfo.textContent = data.error;
                } else {
                    let forecastHtml = `<h2>${data.city} 未来 3 天天气预报</h2>`;
                    data.forecast.forEach(forecast => {
                        forecastHtml += `
                            <p><span>日期:</span> ${forecast.date}</p>
                            <p><span>天气:</span> ${forecast.weather}</p>
                            <p><span>温度:</span> ${forecast.temperature} °C</p>
                        `;
                    });
                    forecastInfo.innerHTML = forecastHtml;
                }
            } catch (error) {
                forecastInfo.textContent = `查询出错: ${error.message}`;
            }
        });

        // 定时刷新功能
        function refreshWeatherData() {
            const listItems = weatherList.querySelectorAll('li');

            listItems.forEach(async (listItem) => {
                const cityElement = listItem.querySelector('p:first-child span + text');
                if (cityElement) {
                    const city = cityElement.textContent.trim();
                    try {
                        const apiUrl = `http://localhost:3000/weather?city=${city}`;
                        const response = await fetch(apiUrl);
                        if (!response.ok) {
                            throw new Error('网络响应不正常');
                        }

                        const data = await response.json();
                        if (data.error) {
                            listItem.textContent = `查询 ${city} 出错: ${data.error}`;
                        } else {
                            listItem.innerHTML = `
                                <div>
                                    <p><span>城市:</span> ${data.city}</p>
                                    <p><span>天气:</span> ${data.weather}</p>
                                    <p><span>温度:</span> ${data.temperature} °C</p>
                                </div>
                            `;
                        }

                        const deleteButton = document.createElement('button');
                        deleteButton.textContent = '删除';
                        deleteButton.classList.add('delete');
                        deleteButton.addEventListener('click', function () {
                            weatherList.removeChild(listItem);
                            updateLocalStorage();
                        });

                        listItem.appendChild(deleteButton);
                        updateLocalStorage();
                    } catch (error) {
                        listItem.textContent = `查询 ${city} 出错: ${error.message}`;
                        const deleteButton = document.createElement('button');
                        deleteButton.textContent = '删除';
                        deleteButton.classList.add('delete');
                        deleteButton.addEventListener('click', function () {
                            weatherList.removeChild(listItem);
                            updateLocalStorage();
                        });
                        listItem.appendChild(deleteButton);
                        updateLocalStorage();
                    }
                }
            });
        }

        // 计算到下一个 0 点或 12 点的时间差
        function getTimeUntilNextRefresh() {
            const now = new Date();
            const hours = now.getHours();
            let nextRefreshHours;
            if (hours < 12) {
                nextRefreshHours = 12;
            } else if (hours < 24) {
                nextRefreshHours = 24;
            }

            const nextRefresh = new Date(now.getFullYear(), now.getMonth(), now.getDate(), nextRefreshHours, 0, 0);
            if (nextRefresh < now) {
                nextRefresh.setDate(nextRefresh.getDate() + 1);
            }
            return nextRefresh - now;
        }

        // 首次定时刷新
        const initialDelay = getTimeUntilNextRefresh();
        setTimeout(() => {
            refreshWeatherData();
            // 之后每 12 小时刷新一次
            setInterval(refreshWeatherData, 12 * 60 * 60 * 1000);
        }, initialDelay);

        // 页面加载时恢复数据
        restoreData();
    </script>
</body>

</html>    